import axios from 'axios'
import { Loading, Message } from 'element-ui'
import Qs from 'qs'
import store from '@/store'

const $axios = axios.create({
    // 设置超时时间
    timeout: 30000,
    // 基础url，会在请求url中自动添加前置链接
    baseURL: 'http://www.lovegf.cn:8888/api/private/v1/'
});

let loading = null;

$axios.interceptors.request.use(function (config) {
    loading = Loading.service({ text: '拼命加载中' });
    // const token = localStorage.getItem('cms-token');
    if (store.state.token) {
        config.headers['Authorization'] = store.state.token;
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

$axios.interceptors.response.use(function (response) {
    if (loading) {
        loading.close()
        const code = response.status
        if ((code >= 200 && code < 300) || code === 304) {
            return Promise.resolve(response.data)
        } else {
            return Promise.reject(response)
        }
    }
}, function (error) {
    if (loading) {
        loading.close()
    }
    if (error.response) {
        switch (error.response.status) {
            case 404:
                Message.error('网络请求不存在')
                break
            default:
                Message.error(error.response.data.message)
        }
    } else {
        // 请求超时或者网络有问题
        if (error.message.includes('timeout')) {
            Message.error('请求超时！请检查网络是否正常')
        } else {
            Message.error('请求失败，请检查网络是否已连接')
        }
    }
    return Promise.reject(error);
});

function post(url, data) {
    return $axios({
        method: 'post',
        url,
        data: Qs.stringify(data),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    })
}

function get(url, params) {
    return $axios({
        method: 'get',
        url,
        params
    })
}

export default {
    post,
    get

}